<template>
  <div class="login-wrapper">
    <el-card class="login-card">
      <h2>登录</h2>

      <el-form ref="FormRef" :model="form" :rules="rules" size="large" @keyup.enter="submit">
        <!-- 账号 -->
        <el-form-item prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" :prefix-icon="User" clearable />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 同意协议框 -->
        <el-form-item prop="isCheck">
          <el-checkbox name="type" v-model="form.isCheck" />
          <a href="javascript:;">我已同意隐私条款和服务条款</a>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" style="width: 100%" :loading="loading" @click="submit">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { loginAPI } from '@/api/user'
import {useRouter} from 'vue-router'
import { useUserStore } from '@/stores/user'
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)

const form = reactive({
  account: 'xiaotuxian001',
  password: '123456',
  isCheck: true,
})

const rules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  isCheck: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意协议'))
        }
        callback()
      },
    },
  ],
}

// 登录提交
const FormRef = ref(null)

const submit = () => {
  FormRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    try {
      const res = await loginAPI({
        account: form.account,
        password: form.password,
      })

      if(res.code === '1'){
        ElMessage.success('登录成功')
        userStore.setUserInfo(res.result)
        router.replace('/')
        
      }else{
        ElMessage.error('登录失败'+res.msg)
      }
    } catch (e) {
     console.log();
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.login-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #f7f8fa;
}
.login-card {
  width: 440px;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}
h2 {
  text-align: center;
  margin: 0 0 24px;
  font-weight: 400;
  color: #303133;
}
</style>
